import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Routes, Route, Link, Navigate, useLocation, Outlet, useNavigate } from "react-router-dom";
import { Layout, Menu, Dropdown, message, Spin } from "antd";
import {
  UploadOutlined,
  BarChartOutlined,
  HomeOutlined,
  UserOutlined,
  LogoutOutlined
} from "@ant-design/icons";
import { useSelector, useDispatch } from 'react-redux';
import { logout, setUserInfo } from './store/slices/userSlice';

import Login from "./pages/Login";
import Home from "./pages/Home";
import NetworkMonitor from "./pages/NetworkMonitor";
import TopologyBuilder from "./pages/TopologyBuilder";
import UserManagement from "./pages/UserManagement";
import Profile from "./pages/Profile";
import { api } from './api';

const { Header, Sider, Content } = Layout;

// 受保护的路由组件
const RequireAuth = ({ children }) => {
  const { token } = useSelector(state => state.user);
  const location = useLocation();

  if (!token) {
    // 如果没有token，重定向到登录页，并记住尝试访问的URL
    return <Navigate to="/login" state={{ from: location.pathname }} replace />;
  }

  return children;
};

// 主布局组件
const MainLayout = () => {
  const dispatch = useDispatch();
  const { userInfo } = useSelector(state => state.user);
  const location = useLocation();
  const navigate = useNavigate();

  // 根据当前路径设置默认选中的菜单项
  const getDefaultSelectedKey = () => {
    const pathname = location.pathname;
    if (pathname.includes('/home')) return "1";
    if (pathname.includes('/topology-builder')) return "2";
    if (pathname.includes('/network-monitor')) return "3";
    if (pathname.includes('/user-management')) return "4";
    if (pathname.includes('/profile')) return "5";
    return "1"; // 默认选中首页
  };

  const [selectedKey, setSelectedKey] = useState(getDefaultSelectedKey());

  // 当路径变化时更新选中的菜单项
  useEffect(() => {
    setSelectedKey(getDefaultSelectedKey());
  }, [location.pathname]);

  // 处理菜单项点击
  const handleMenuClick = (key) => {
    setSelectedKey(key);
  };

  const handleLogout = async () => {
    try {
      await api.logout();
      dispatch(logout());
      message.success('退出成功');
      // 退出后跳转到登录页
      window.location.href = '/login';
    } catch (error) {
      console.error("退出失败:", error);
      // 即使API调用失败，也清除本地状态
      dispatch(logout());
      // 退出后跳转到登录页
      window.location.href = '/login';
    }
  };

  const userMenu = (
    <Menu>
      <Menu.Item key="profile" onClick={() => {
        setSelectedKey("5");
        navigate("/profile");
      }}>
        个人中心
      </Menu.Item>
      <Menu.Item key="logout" onClick={handleLogout}>
        <LogoutOutlined /> 退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Header style={{
        padding: '0 24px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div className="logo" style={{ color: 'white', fontSize: '18px', fontWeight: 'bold' }}>
          网络攻击仿真系统
        </div>
        <Dropdown overlay={userMenu} trigger={['click']}>
          <span style={{ color: 'white', cursor: 'pointer' }}>
            <UserOutlined /> {userInfo?.username || '用户'}
          </span>
        </Dropdown>
      </Header>

      <Layout>
        <Sider>
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={[selectedKey]}
            onClick={({ key }) => handleMenuClick(key)}
          >
            <Menu.Item key="1" icon={<HomeOutlined />}>
              <Link to="/home">首页</Link>
            </Menu.Item>
            <Menu.Item key="2" icon={<UploadOutlined />}>
              <Link to="/topology-builder">拓扑构建</Link>
            </Menu.Item>
            <Menu.Item key="3" icon={<BarChartOutlined />}>
              <Link to="/network-monitor">网络监控</Link>
            </Menu.Item>
            <Menu.Item key="4" icon={<UserOutlined />}>
              <Link to="/user-management">用户管理</Link>
            </Menu.Item>
            <Menu.Item key="5" icon={<UserOutlined />}>
              <Link to="/profile">个人中心</Link>
            </Menu.Item>
          </Menu>
        </Sider>

        <Content style={{ margin: "16px" }}>
          <Outlet /> {/* 使用Outlet来渲染子路由 */}
        </Content>
      </Layout>
    </Layout>
  );
};

// 重定向组件
const RedirectToHome = () => {
  return <Navigate to="/home" replace />;
};

const App = () => {
  const dispatch = useDispatch();
  const { token } = useSelector(state => state.user);
  const [loading, setLoading] = useState(true);
  const [initialized, setInitialized] = useState(false);

  // 如果有token，尝试获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      if (token) {
        try {
          // 检查是否有缓存的网络状态
          const cachedNetworkState = localStorage.getItem('networkState');

          // 获取用户信息
          const res = await api.getUserInfo();
          if (res.code === 0 || res.code === 200) {
            dispatch(setUserInfo(res.data));

            // 如果没有缓存的网络状态，则重置网络状态
            if (!cachedNetworkState) {
              console.log('没有缓存的网络状态，重置网络状态');
              // 导入resetNetworkState action
              const { resetNetworkState } = require('./store/slices/networkSlice');
              dispatch(resetNetworkState());
            }
          } else {
            // 如果获取用户信息失败，可能是token无效，清除token
            console.error("获取用户信息失败，清除token");
            dispatch(logout());
          }
        } catch (error) {
          console.error("获取用户信息失败:", error);
          // 如果出错，也清除token
          dispatch(logout());
        }
      }
      // 无论结果如何，都设置loading为false
      setLoading(false);
      setInitialized(true);
    };

    fetchUserInfo();
  }, [token, dispatch]);

  // 显示加载状态
  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  // 确保应用已初始化
  if (!initialized) {
    return null;
  }

  return (
    <Router>
      <Routes>
        {/* 登录页面路由 */}
        <Route path="/login" element={
          token ? <Navigate to="/home" replace /> : <Login />
        } />

        {/* 主布局路由 */}
        <Route
          path="/"
          element={
            <RequireAuth>
              <MainLayout />
            </RequireAuth>
          }
        >
          {/* 子路由 */}
          <Route path="home" element={<Home />} />
          <Route path="topology-builder" element={<TopologyBuilder />} />
          <Route path="network-monitor" element={<NetworkMonitor />} />
          <Route path="user-management" element={<UserManagement />} />
          <Route path="profile" element={<Profile />} />
          <Route index element={<RedirectToHome />} />
          <Route path="*" element={<RedirectToHome />} />
        </Route>
      </Routes>
    </Router>
  );
};

export default App;
